package jp.co.realsys.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import jp.co.realsys.error.TaskException;
import jp.co.realsys.model.UserModel;
import jp.co.realsys.service.UsersinfoService;

import com.opensymphony.xwork2.ActionSupport;

@Controller
public class LoginAction extends ActionSupport implements SessionAware {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
	private UsersinfoService userService;

	private UserModel user; 
	
	SessionMap<String,String> session;
	//Map<String, Object> session = ActionContext.getContext().getSession();
	
	public String login() throws TaskException {
		if (user == null) {
			return INPUT;
		}
		boolean isUser = userService.doCheckUser(user);
		String loginMessage = "";
		if (isUser) {
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd　HH:mm:ss");
			loginMessage = "よこそう、" + user.getUserId() + "さん。" + sdf.format(dt);
			//Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("loginMessage", loginMessage);
			//session.put("isLogin", user.getUserId());
		}else{
			throw new TaskException("ログイン失敗しました");
		}
		return SUCCESS;
	}
	
	public String logout(){ 
		/*
		Map<String, Object> session = ActionContext.getContext().getSession(); 
		session.clear();
	    user.setUserId(null);
	    user.setPassword(null);
	    */
		session.invalidate();
	    return SUCCESS;  
	} 
	
	public UserModel getUser() {
		return user;
	}

	public void setUser(UserModel user) {
		this.user = user;
	}

	@Override
	public void setSession(Map map) {
		session = (SessionMap) map;  
	    session.put("login","true");
	}
}
